package com.igeek.ch02.servlet;

import com.igeek.ch02.entity.User;
import com.igeek.ch02.service.UserService;
import com.igeek.ch02.utils.DateConverterUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;

@WebServlet(name = "UserServlet", value = "/user")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置中文友好
        //request.setCharacterEncoding("UTF-8");
        //response.setContentType("text/html;charset=UTF-8");

        //获取会话
        HttpSession session = request.getSession();

        //获取请求参数
        String method = request.getParameter("method");
        if(method!=null && !method.equals("")){
            switch (method){
                case "login":
                    System.out.println("用户登录");
                    String username = request.getParameter("username");
                    String address = request.getParameter("address");
                    System.out.println("username = "+username+" , address = "+address);
                    User user = userService.login(username, address);
                    if(user!=null){
                        //将登录成功的信息，传递到页面，设置请求属性
                        request.setAttribute("user" , user);
                        //将登录成功的信息，传递到页面，设置会话属性
                        session.setAttribute("sessionUser" , user);

                        //请求转发
                        request.getRequestDispatcher("success.jsp").forward(request,response);
                        //思考问题？ 响应重定向，请求域 和  会话域 哪一个数据会被传递下去？？？  会话域
                    }else{
                        response.sendRedirect("error.jsp");
                    }
                    break;
                case "register":
                    System.out.println("用户注册");
                    //批量收集表单数据  Key是input的name属性、Value是表单中填写的值
                    Map<String, String[]> parameterMap = request.getParameterMap();
                    //String --> Date
                    ConvertUtils.register(new DateConverterUtils() , Date.class);
                    //Map<String, String[]> --> User
                    User u = new User();
                    try {
                        //拷贝属性至User对象
                        BeanUtils.populate(u , parameterMap);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    System.out.println("u = "+u);

                    if(u!=null && u.getUsername()!=null && !u.getUsername().equals("") && u.getAddress()!=null && !u.getAddress().equals("")) {
                        boolean flag = userService.register(u);
                        if(flag){
                            //登录界面的姓名回显
                            session.setAttribute("username" , u.getUsername());
                            response.sendRedirect("/login.jsp");
                        }else{
                            response.sendRedirect("/error.jsp");
                        }
                    }

                    /*username = request.getParameter("username");
                    address = request.getParameter("address");
                    String sex = request.getParameter("sex");
                    String birthdayStr = request.getParameter("birthday");

                    //业务调用
                    if(username!=null && !username.equals("") && address!=null && !address.equals("") && birthdayStr!=null && !birthdayStr.equals("")){
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date birthday = null;
                        try {
                            birthday = sdf.parse(birthdayStr);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        User u = new User(username , birthday , sex , address);
                        boolean flag = userService.register(u);
                        if(flag){
                            //登录界面的姓名回显
                            session.setAttribute("username" , username);
                            response.sendRedirect("/login.jsp");
                        }else{
                            response.sendRedirect("/error.jsp");
                        }
                    }*/
                    break;
                case "logout":
                    System.out.println("用户登出");
                    //销毁会话信息
                    session.invalidate();
                    response.sendRedirect("login.jsp");
                    break;
                case "validate":
                    System.out.println("用户姓名校验");
                    //校验姓名是否存在
                    username = request.getParameter("username");
                    boolean flag = userService.validateName(username);
                    PrintWriter out = response.getWriter();
                    //json格式数据  {"flag":flag}
                    out.println("{\"flag\":"+flag+"}");
                    out.flush();
                    out.close();
                    break;

            }
        }
    }
}
